package com.lanou3g.zjl.chating.home.chatwindow.child;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.util.ImageUtils;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.home.friends.EaseConstant;
import com.lanou3g.zjl.chating.utils.EaseCommonUtils;
import com.lanou3g.zjl.chating.utils.OnItemClickListener;
import com.lanou3g.zjl.chating.utils.SmileUtils;
import com.lanou3g.zjl.chating.volley.VolleySingleton;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created by dllo on 15/11/21.
 */
public class ChatWindowFrgRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /**
     * 数据类型的静态标识符
     */
    private static final int MESSAGE_TYPE_RECV_TXT = 0;
    private static final int MESSAGE_TYPE_SEND_TXT = 1;
    private static final int MESSAGE_TYPE_RECV_IMAGE = 2;
    private static final int MESSAGE_TYPE_SEND_IMAGE = 3;
    private static final int MESSAGE_TYPE_RECV_LOCATION = 4;
    private static final int MESSAGE_TYPE_SEND_LOCATION = 5;
    private static final int MESSAGE_TYPE_RECV_VOICE = 6;
    private static final int MESSAGE_TYPE_SEND_VOICE = 7;
    private static final int MESSAGE_TYPE_RECV_VIDEO = 8;
    private static final int MESSAGE_TYPE_SEND_VIDEO = 9;
    private static final int MESSAGE_TYPE_RECV_FILE = 10;
    private static final int MESSAGE_TYPE_SEND_FILE = 11;
    private static final int MESSAGE_TYPE_RECV_EXPRESSION = 12;
    private static final int MESSAGE_TYPE_SEND_EXPRESSION = 13;

    private ImageLoader imageLoader;
    private OnItemClickListener onItemClickListener;

    private List<EMMessage> emMessages;
    private EMMessage message;
    private Context context;
    private int msgType = 100;
//    private List<Integer> id;
//    private String picturePath;


    public ChatWindowFrgRvAdapter(Context c) {
        this.context = c;
        imageLoader = VolleySingleton.getInstance(c).getImageLoader();
    }

    public void addData(List<EMMessage> emMessages) {
        this.emMessages = emMessages;
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
        View view;
        LayoutInflater inflater = LayoutInflater.from(context);
        switch (msgType) {
            case 0:
                view = inflater.inflate(R.layout.chatwindowrv_receive_txt_item, null);
                return new VHReceiveMsg(view);

            case 1:
                view = inflater.inflate(R.layout.chatwindowrv_send_txt_item, null);
                return new VHSendMsg(view);

            case 2:
                view = inflater.inflate(R.layout.chatwindowrv_receive_img_item, null);
                return new VHReceiveImg(view);

            case 3:
                view = inflater.inflate(R.layout.chatwindowrv_send_img_item, null);
                return new VHSendImg(view);

            case 4:
                view = inflater.inflate(R.layout.chatwindowrv_receive_location_item, null);
                return new VHReceiveLocation(view);

            case 5:
                view = inflater.inflate(R.layout.chatwindowrv_send_location_item, null);
                return new VHSendLocation(view);

            case 6:
                view = inflater.inflate(R.layout.chatwindowrv_receive_voice_item, null);
                return new VHReceiveVoice(view);

            case 7:
                view = inflater.inflate(R.layout.chatwindowrv_send_voice_item, null);
                return new VHSendVoice(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        message = emMessages.get(position);
        switch (msgType) {
            case 0://收文字
                TextMessageBody txtReceiveBody = (TextMessageBody) message.getBody();
                VHReceiveMsg vhReceiveMsg = (VHReceiveMsg) holder;
//                Spannable span = SmileUtils.getSmiledText(context, txtReceiveBody.getMessage());
//                vhReceiveMsg.receiveMessage_Content.setText(span, TextView.BufferType.SPANNABLE);
                String emojiconName = txtReceiveBody.getMessage();
                if (emojiconName.contains("ee_")) {

                    int resId = context.getResources().getIdentifier(emojiconName, "mipmap", context.getPackageName());
                    Bitmap bitmap = null;
                    bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                    ImageSpan imageSpan = new ImageSpan(context, bitmap);

                    SpannableString spannableString =
                            new SpannableString(emojiconName);

                    spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    if (emojiconName != "delete_expression") {
                    vhReceiveMsg.receiveMessage_Content.setText(spannableString);
//                    }
                } else {
                    vhReceiveMsg.receiveMessage_Content.setText(txtReceiveBody.getMessage());
                }
//                if (emojiconName == "delete_expression" && chat_Et.getText().length() >= 5) {
//                    String readySend = chat_Et.getText().toString();
//                    int sendLen = chat_Et.getText().length() - 5;
//                    if (sendLen >= 5) {
//                        String send = readySend.substring(0, sendLen);
//                        int resId_ready = getResources().getIdentifier(send, "mipmap", getActivity().getPackageName());
//                        Bitmap bitmap_ready = BitmapFactory.decodeResource(getResources(), resId_ready);
//                        ImageSpan span = new ImageSpan(getActivity(), bitmap_ready);
//                        SpannableString string = new SpannableString(send);
//                        string.setSpan(span, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                        chat_Et.setText(string);
//                        chat_Et.setSelection(chat_Et.getText().length());
//                    } else if (sendLen == 0) {
//                        chat_Et.setText("");
//                    }
//
//                }
                break;

            case 1://发文字
                TextMessageBody txtSendBody = (TextMessageBody) message.getBody();
                VHSendMsg vhSendMsg = (VHSendMsg) holder;
//                String str_emtion[] = chatMessage.getFromUsre_Con().split("\"");
//                Spannable span1 = SmileUtils.getSmiledText(context, txtSendBody.getMessage());
//                vhSendMsg.sendMsg_Content.setText(span1, TextView.BufferType.SPANNABLE);

                String emojiconName1 = txtSendBody.getMessage();
                int l = emojiconName1.length();
                if (emojiconName1.contains("ee_")) {

                    int resId1 = context.getResources().getIdentifier(emojiconName1, "mipmap", context.getPackageName());
                    Bitmap bitmap1 = null;
                    bitmap1 = BitmapFactory.decodeResource(context.getResources(), resId1);
                    ImageSpan imageSpan1 = new ImageSpan(context, bitmap1);

                    SpannableString spannableString1 =
                            new SpannableString(emojiconName1);

                    spannableString1.setSpan(imageSpan1, 0, l, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    if (emojiconName1 != "delete_expression") {
                    vhSendMsg.sendMsg_Content.setText(spannableString1);
//                    }
                } else {
                    vhSendMsg.sendMsg_Content.setText(txtSendBody.getMessage());
                }
                break;

            case 2:
                VHReceiveImg vhReceiveImg = (VHReceiveImg) holder;
                ImageMessageBody imgReceiveBody = (ImageMessageBody) message.getBody();
                String remotePath = imgReceiveBody.getRemoteUrl();
                getBitmapCache(remotePath, vhReceiveImg.receiveImg_Content);
                break;

            case 3:
                VHSendImg vhSendImg = (VHSendImg) holder;
                ImageMessageBody imgSendBody = (ImageMessageBody) message.getBody();
                String sendFilePath = imgSendBody.getLocalUrl();
                if (sendFilePath != null) {
                    vhSendImg.sendImg_Content.setImageBitmap(BitmapFactory.decodeFile(sendFilePath));
                }
                break;

            case 4:
                VHReceiveLocation vhReceiveLocation = (VHReceiveLocation) holder;
                LocationMessageBody locationReceiveBody = (LocationMessageBody) message.getBody();
                vhReceiveLocation.receiveLocation_Tv.setText(locationReceiveBody.getAddress());
                break;

            case 5:
                VHSendLocation vhSendLocation = (VHSendLocation) holder;
                LocationMessageBody locationSendBody = (LocationMessageBody) message.getBody();
                vhSendLocation.sendLocation_TV.setText(locationSendBody.getAddress());
                break;

            case 6:
                final VHReceiveVoice vhReceiveVoice = (VHReceiveVoice) holder;
                VoiceMessageBody voiceReceiverBody = (VoiceMessageBody) message.getBody();
                int timeReceiver = voiceReceiverBody.getLength();
                vhReceiveVoice.receiveVoice_Tv.setText(timeReceiver + "\"");

                vhReceiveVoice.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = vhReceiveVoice.getPosition();

                        message = emMessages.get(position);
                        if (playMsgId != null && playMsgId.equals(message.getMsgId())) {
                            stopPlayVoice();
                            return;
                        }
                        VoiceMessageBody voiceSendBody = (VoiceMessageBody) message.getBody();
                        File file = new File(voiceSendBody.getLocalUrl());
                        if (file.exists() && file.isFile()) {
                            playVoice(voiceSendBody.getLocalUrl());
                        }
                    }
                });
                break;

            case 7:
                final VHSendVoice vhSendVoice = (VHSendVoice) holder;
                VoiceMessageBody voiceSendBody = (VoiceMessageBody) message.getBody();
                int timeSend = voiceSendBody.getLength();
                vhSendVoice.sendVoice_Tv.setText(timeSend + "\"");

                vhSendVoice.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = vhSendVoice.getPosition();

                        message = emMessages.get(position);
                        if (playMsgId != null && playMsgId.equals(message.getMsgId())) {
                            stopPlayVoice();
                            return;
                        }
                        VoiceMessageBody voiceSendBody = (VoiceMessageBody) message.getBody();
                        File file = new File(voiceSendBody.getLocalUrl());
                        if (file.exists() && file.isFile()) {
                            playVoice(voiceSendBody.getLocalUrl());
                        }
                    }
                });
        }
    }

//    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
//        this.onItemClickListener = onItemClickListener;
//    }

    private void getBitmapCache(String url, ImageView imageView) {
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(
                imageView, R.mipmap.default_img, R.mipmap.default_img
        );
        imageLoader.get(url, listener);
    }


    //===============所有布局的内部类================================================================================

    /**
     * 收文本消息
     */
    class VHReceiveMsg extends RecyclerView.ViewHolder {
        @Bind(R.id.receiveMessage_Content)
        TextView receiveMessage_Content;

        public VHReceiveMsg(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }

    }

    /**
     * 发文本消息
     */
    class VHSendMsg extends RecyclerView.ViewHolder {
        @Bind(R.id.sendMsg_Content)
        TextView sendMsg_Content;

        public VHSendMsg(View v) {
            super(v);
            sendMsg_Content = (TextView) v.findViewById(R.id.sendMsg_Content);
            ButterKnife.bind(this, v);
        }
    }

    /**
     * 收图片消息
     */
    class VHReceiveImg extends RecyclerView.ViewHolder {
        @Bind(R.id.receiveImg_Content)
        ImageView receiveImg_Content;

        public VHReceiveImg(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }

    /**
     * 发图片消息
     */
    class VHSendImg extends RecyclerView.ViewHolder {
        @Bind(R.id.sendImg_Content)
        ImageView sendImg_Content;

        public VHSendImg(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }

    /**
     * 收位置消息
     */
    class VHReceiveLocation extends RecyclerView.ViewHolder {
        @Bind(R.id.receiveLocation_Iv)
        ImageView receiveLocation_Iv;
        @Bind(R.id.receiveLocation_Tv)
        TextView receiveLocation_Tv;

        public VHReceiveLocation(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }

    /**
     * 发位置消息
     */
    class VHSendLocation extends RecyclerView.ViewHolder {
        @Bind(R.id.sendLocation_Iv)
        ImageView sendLocation_Iv;
        @Bind(R.id.sendLocation_TV)
        TextView sendLocation_TV;

        public VHSendLocation(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }

    /**
     * 收语音消息
     */
    class VHReceiveVoice extends RecyclerView.ViewHolder {
        @Bind(R.id.receiveVoice_Content)
        ImageView receiveVoice_Content;
        @Bind(R.id.receiveVoice_Tv)
        TextView receiveVoice_Tv;

        public VHReceiveVoice(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }

    /**
     * 发语音消息
     */
    class VHSendVoice extends RecyclerView.ViewHolder {
        @Bind(R.id.sendVoice_Content)
        ImageView sendVoice_Content;
        @Bind(R.id.sendVoice_Tv)
        TextView sendVoice_Tv;

        public VHSendVoice(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }
//------------------所有布局的内部类------------------------------------------------------------------------

    @Override
    public int getItemCount() {
        return emMessages != null && emMessages.size() > 0 ? emMessages.size() : 0;
    }

    @Override
    public int getItemViewType(int position) {
        message = emMessages.get(position);
        switch (message.getType()) {
            case TXT:
                if (message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                    msgType = message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_EXPRESSION : MESSAGE_TYPE_SEND_EXPRESSION;
                }
                msgType = message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SEND_TXT;
                return msgType;

            case LOCATION:
                msgType = message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LOCATION : MESSAGE_TYPE_SEND_LOCATION;
                return msgType;

            case FILE:

                break;

            case IMAGE:
                msgType = message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_IMAGE : MESSAGE_TYPE_SEND_IMAGE;
                return msgType;

            case VOICE:
                msgType = message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE : MESSAGE_TYPE_SEND_VOICE;
                return msgType;

            case VIDEO:
                break;

            default:
                break;
        }
        return super.getItemViewType(position);
    }

    private String playMsgId;
    private MediaPlayer mediaPlayer;
//    private boolean isPlaying = false;

    /**
     * 播放语音
     */
    public void playVoice(String filePath) {
        if (!(new File(filePath).exists())) {
            return;
        }
        // 语音的id
        playMsgId = message.getMsgId();
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        mediaPlayer = new MediaPlayer();

        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    stopPlayVoice();
                }

            });

            mediaPlayer.start();

            // 如果是接收的消息
            if (message.direct == EMMessage.Direct.RECEIVE) {
                try {
                    if (!message.isAcked) {
                        message.isAcked = true;
                        // 告知对方已读这条消息
//                        if (msgType != EMMessage.msgType.GroupChat && msgType != EMMessage.msgType.ChatRoom)
//                            EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                    }
                } catch (Exception e) {
                    message.isAcked = false;
                }
//                if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
//                    // 隐藏自己未播放这条语音消息的标志
//                    iv_read_status.setVisibility(View.INVISIBLE);
//                    EMChatManager.getInstance().setMessageListened(message);
//                }
            }

        } catch (Exception e) {
            System.out.println();
        }
    }

    /**
     * 停止播放语音
     */
    private void stopPlayVoice() {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
//        isPlaying = false;
        playMsgId = null;
        notifyDataSetChanged();
    }


}
